package server

import (
	"gitee.com/perception-network/block-chain-released/internal/handler"
	"gitee.com/perception-network/block-chain-released/internal/repository"
	"gitee.com/perception-network/block-chain-released/internal/service"
	"github.com/Ankr-network/kit/app"
	"github.com/Ankr-network/kit/rest"
	"github.com/Ankr-network/kit/rpc"
	"github.com/spf13/cobra"
)

func NewServer() *cobra.Command {
	var cmd = &cobra.Command{
		Use:   "server",
		Short: "",
		Long:  ``,
		Args:  cobra.NoArgs,
		Run:   run,
	}

	return cmd
}

func run(cmd *cobra.Command, args []string) {
	log.Info("init repo")
	repository.GlobalInit()

	log.Info("init service")
	service.GlobalInit()

	log.Info("init handler")
	handler.InitGlobal()

	log.Info("register grpc")
	rpcServer := rpc.NewServerWithConfig()
	handler.RegisterGRPC(rpcServer.Server)

	log.Info("grpc runnig...")
	rpcServer.MustListenAndServe()

	log.Info("register rest")
	restServer := rest.NewServerWithConfig()
	handler.MustRegisterREST(restServer.ServeMux, rpcServer.Address)

	restServer.ListenAndServed()

	app.Exit()
}
